<template>
	<view :class="['lazy-image']">
		<view :class="[`lazy-${unique}`, 'lazy-image__inner']">
			<image v-if="showTruePic && src" class="image-context" :src="$img_base_url(src)" @error="handleImgError" :mode="mode" />
			<image class="image-context image-fial" :src="$img_path('/common/loadfail.png')"
				v-else-if="isLoadError || !src" />
			<image class="image-context" :src="$img_path('/common/loading.gif')" v-else />
		</view>
	</view>
</template>

<script>
	export default {
		name: "laye-image",
		props: {
			unique: {
				type: [String, Number],
				default: () => "0",
			},
			src: {
				type: String,
				required: true,
			},
			mode: {
				type: String,
				default: () => "aspectFill"
			},
		},
		data() {
			return {
				isLoadError: false,
				// 是否展示真实地址
				showTruePic: false,
				loadfailUrl: "",
				loadingUrl: ""
			};
		},
		mounted() {
			this.loadfailUrl = this.$img_path('/common/loadfail.png')
			this.loadingUrl = this.$img_path('/common/loading.gif')
			// console.log("this.loadfailUrl", this.loadfailUrl)
			// console.log("this.loadingUrl", this.loadingUrl)
			this.$nextTick(() => {
				this.observerImage();
			})
		},
		methods: {
			handleImgError() {
				this.isLoadError = true;
				this.showTruePic = !this.showTruePic
				console.log("图片加载失败", this.loadfailUrl)
			},

			observerImage() {
				const observer = uni.createIntersectionObserver(this);
				observer.relativeToViewport();
				observer.observe('.lazy-' + this.unique, (res) => {
					if (res.intersectionRatio > 0) {
						this.showTruePic = true;
					}
				});
			}
		}
	}
</script>

<style scoped>
	.lazy-image {
		/* // 微信小程序不设置这个会炸裂 */
		width: 100%;
		height: 100%;

	}

	.lazy-image__inner {
		width: 100%;
		height: 100%;
	}

	.image-context {
		width: 100%;
		height: 100%;
	}
</style>